// Copyright 2023 Srhino Co., Ltd. All rights reserved.

package webserver

import (
	"context"
	"fmt"
	"git.ouryun.cn/lzj1/grpc-bidirectional-stream/pkg/apis/v2"
	ifacev2 "git.ouryun.cn/lzj1/grpc-bidirectional-stream/pkg/interfaces/v2"
	v22 "git.ouryun.cn/lzj1/grpc-bidirectional-stream/pkg/services/v2"
	"io"
	"log"
	"net/http"
	"ouryun.com/web-demov2/utils"
)

type Server struct {
	addr string
	port uint32
	ctx  context.Context
	gs   ifacev2.GrpcServer
}

func NewServer(addr string, port uint32, gs ifacev2.GrpcServer) *Server {
	return &Server{
		addr: addr,
		port: port,
		ctx:  context.Background(),
		gs:   gs,
	}
}

func (s *Server) SetGs(gs ifacev2.GrpcServer) {
	s.gs = gs
}

func (s *Server) Start() error {
	config := &utils.RestServerConfig{
		Name:    "stream-demo",
		Address: fmt.Sprintf("%s:%d", s.addr, s.port),
	}
	utils.Logger.Infof("%+v", s.gs)
	restServer := utils.NewRestServer(s.ctx, config)
	restServer.RegisterHandlerFunc("/user", s.User)
	if err := restServer.Start(); err != nil {
		return err
	}
	return nil
}

func (s *Server) User(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	respResult := utils.NewEmptyResponseResult()
	defer func() {
		if r := recover(); r != nil {
			utils.Logger.Error(r)
			respResult.Err = r.(error).Error()
			w.WriteHeader(http.StatusInternalServerError)
			if _, err := w.Write(respResult.Bytes()); err != nil {
				utils.Logger.Error(err)
			}
		}
	}()

	// 读取请求的 Body
	body, err := io.ReadAll(r.Body)
	defer r.Body.Close()
	req := &v2.StreamMessage_Request{
		Request: &v2.Request{},
	}

	if err != nil {
		utils.Logger.Error(err)
		respResult.Err = err.Error()
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	// TODO 这里需要根据不同的请求，构建不同的结构体
	req.Request.Body = body
	req.Request.Url = r.URL.Path
	req.Request.Method = r.Method

	params := make(map[string]string)
	for k, v := range r.URL.Query() {
		params[k] = v[0]
	}
	req.Request.Params = params
	headers := make(map[string]string)
	for k, v := range r.Header {
		headers[k] = v[0]
	}
	req.Request.Headers = headers

	message := &v2.StreamMessage{
		ServerType: v22.CLIENT_TYPE_WEBSERVER,
		Message:    req,
	}

	// 构建grpc消息, 并发送到grpc客户端
	resp, err := s.gs.Request(message, 0)

	log.Printf("resp:%v err:%v", resp, err)

	if err != nil {
		respResult.Err = err.Error()
		w.WriteHeader(http.StatusInternalServerError)
		if _, err := w.Write(respResult.Bytes()); err != nil {
			utils.Logger.Error(err)
		}
		return
	}
	res := resp.Message.(*v2.StreamMessage_Response).Response
	if res.Code != v2.Response_SUCCESS_CODE {
		respResult.Err = res.Error
	} else {
		respResult.Data = res.Body
	}

	if _, err := w.Write(respResult.Bytes()); err != nil {
		utils.Logger.Error(err)
	}
}

func (s *Server) Callback(message *v2.StreamMessage) {
	utils.Logger.Infof("callback: %v", message)
	request := message.GetRequest()

	resp := &v2.StreamMessage{
		ServerType: message.Source,
		Message: &v2.StreamMessage_Response{
			Response: &v2.Response{
				Code:  v2.Response_SUCCESS_CODE,
				Body:  request.Body,
				Error: fmt.Sprintf("this is %s", v22.CLIENT_TYPE_WEBSERVER),
			},
		},
		Source: v22.CLIENT_TYPE_WEBSERVER,
	}

	_, err := s.gs.Request(resp, message.RequestId)
	if err != nil {
		return
	}
}
